<?php
namespace App\Services;

use AntChain\TWC\Client as AntChainTWCClient;

use AntChain\TWC\Models\Config;
use AntChain\TWC\Models\BclContactInfo;
use AntChain\TWC\Models\RegisterBclMerchantRequest;
use AntChain\TWC\Models\GetBclUploadurlRequest;
use AntChain\TWC\Models\CreateBclProductRequest;
use AntChain\TWC\Models\QueryBclProductRequest;
use AntChain\TWC\Models\CreateBclOrderRequest;
use AntChain\TWC\Models\SubmitBclOrderRequest;
use AntChain\TWC\Models\QueryBclOrderRequest;
use AntChain\TWC\Models\AddBclLogisticinfoRequest;
use AntChain\TWC\Models\UpdateBclPromiserepaymentRequest;
use App\Models\GoodsSetmeal;
use App\Models\MemberOther;
use App\Models\Order;
use App\Models\OrderLease;
use AntChain\TWC\Models\BclCreatePromiseDetailInfo;
use AntChain\TWC\Models\BclOrderProductInfo;
use AntChain\TWC\Models\BclUserInfo;
use antcloud\AntCloudSDKCore\AntCloudClient;
use AntChain\TWC\Models\UploadBclPerformanceRequest;


/**
 * 租赁宝PULS服务
 */
class AntchainPlusService {
    protected $AntChainTWCClient;
    public function __construct(){
        $config = new Config([]);
        // 您的AccessKey ID
        $config->accessKeyId = config('antchain.accessKeyId');
        // 您的AccessKey Secret
        $config->accessKeySecret = config('antchain.accessKeySecret');
        $config->endpoint=config('antchain.endpoint');
        $this->AntChainTWCClient=new AntChainTWCClient($config);
    }

    /**
     * 智能合同日志记录
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function requestLog($message,$request=[],$response=[])
    {
        $content = [
            'request'=>is_object($request) ? object_array($request) : $request,
            'response'=>is_object($response) ? object_array($response) : $response,
        ];
        \Illuminate\Support\Facades\Log::debug($message,$content);
    }

    /**
     * 上传租赁宝租赁信息代扣
     * @param $order
     * @return false|string|void
     */
 public static  function uploadAntchainPlusOrder($orderId){
        $order = Order::from('sp_order_2 as o')->where('o.id',$orderId)
            ->leftjoin('sp_order_credit as c','c.order_id','o.id')
            ->leftjoin('sp_member_2 as u','o.uid','u.id')
            ->leftjoin('sp_shop_user_2 as su','o.seller_id','su.member_id')
            ->leftjoin('sp_order_goods_2 as og','o.id','og.order_id')
            ->leftjoin('sp_goods_2 as g','og.goods_id','g.id')
            ->select(
                'o.id','o.trade_no','o.begin_time','o.end_time','o.pact_url_3','o.uid','o.seller_id','o.is_insurance_choose','o.is_insurance_choose_custom',
                'o.flow_id','o.mobile','o.user_email','o.sign_num','o.address','o.rent_total','o.month_total','o.amount','o.realname','o.rent_total',
                'o.foregift','o.status','o.prov','o.city','o.area','o.sign_status','o.is_rent_choose'
                ,'c.platformLoanNo','o.create_time'
                ,'u.ant_user_id','u.mobile as user_mobile','u.id as x_user_id','u.cert_name','u.user_id','u.cert_no','u.esign_user_id'
                ,'u.idcard_front','u.idcard_back','og.pact_type','og.is_buy_out','og.goods_title','og.setmeal_title','og.lease_set','og.setmeal_price','og.setmeal_foregift',
                'og.goods_id','og.setmeal_id','og.id as order_goods_id','og.spec_id','og.lease_price','og.lease_time','og.website_price','og.start_date'
                ,'su.mechanism','su.faname','su.shopname','su.contact_tel','su.company','su.company_area','su.companyid','su.id as shop_user_id'
                ,'su.ant_user_id as mer_ant_id'
                ,'g.new_grade')
            ->first();
        $order = $order ? $order->toArray() : [];


        $alipay_user_id=$order['user_id'];
        if(!empty($alipay_user_id)){
            $goodsData=[
                "productVersion" => "1",//商品版本
                "productUrl" => "alipays://platformapi/startapp?appId=2021004105651180&page=pagesA%2Fpages%2FproductDetails%2FproductDetails%3F__appxPageId%3D1%26goodsId%3D".$order['goods_id'],//商品链接
                "productDetailInfo" => $order['setmeal_title'],//商品详情
                "productOrigin" => "SUPPLIER",//商品来源
                "productPrice" =>bcmul($order['rent_total'],130),//商品官网价格，单位：分
                "mainClass" => "3C",//一级行业代码
                "subClass" => "3c_mobile",//二级行业代码
                "productName" => $order['setmeal_title'],//商品名称
                "estimatedShipment" => 50,//预估出货量
                "productOuterId" => $order['setmeal_id'],//商品编码
                "realStock" => 1000,//实际库存量
                "productBrand" => "iphone",//商品品牌
//                "depositPrice" => 1,//免押金额，单位：分
                "supplierName" => $order['shopname'],//供应商名称
                "supplierId" => $order['shop_user_id'],//供应商数字科技租户ID商品从供应商采购为供应商租户ID，否则为平台自己租户ID
                "productModel" => $order['setmeal_id']//产品规格
            ];

            $productId= GoodsSetmeal::where('id',$order['setmeal_id'])->value('ant_product_id');
            if(!$productId){
                $goodsRes=self::createProduct($goodsData);
                $goodsRes=obToArray($goodsRes);
                GoodsSetmeal::where('id',$order['setmeal_id'])->update(['ant_product_id'=>$goodsRes['productId']]);
                $productId=$goodsRes['productId'];
            }
            $bclOrderProductInfo0 = new BclOrderProductInfo([
                "productId" => $productId,//创建商品后返回的商品ID
                "productNumber" => 1//商品数量
            ]);

            $bclCreatePromiseDetailInfo=[];
            $OrderLease=OrderLease::where('order_id',$order['id'])->select('id','begin_time','rent','which_period')->get();
            $OrderLease=obToArray($OrderLease);
            $amount_rent=0;
            foreach ($OrderLease as $i=>$ra){

                $amount_rent+=bcmul($ra['rent'],100);
                if($ra['which_period']==1){
                    $ra['begin_time']=time()+1800;
                }
                $bclCreatePromiseDetailInfo[]= new BclCreatePromiseDetailInfo([
                    "amount" =>bcmul($ra['rent'],100),//承诺金额，单位:分
                    "period" => $ra['which_period'],//承诺期数
                    "promiseTime" => date('c',$ra['begin_time'])
                ]);

            }
            if(!$order['idcard_back']||!$order['idcard_front']){
                return ['status'=>0, 'message'=>'身份证照片未上传'];
            }

            $alipay_idcard_back=self::getBclUploadurl(config('alipay.oss.imgHost').$order['idcard_back'],$order['idcard_back']);
            if($alipay_idcard_back['status']!=200){
                return ['status'=>0, 'message'=>$alipay_idcard_back['fileId']];
            }

            $alipay_idcard_front=self::getBclUploadurl(config('alipay.oss.imgHost').$order['idcard_front'],$order['idcard_front']);
            if($alipay_idcard_front['status']!=200){
                return ['status'=>0, 'message'=>$alipay_idcard_front['fileId']];
            }

            $bclUserInfo = new BclUserInfo([
                "userAccountId" => $order['user_id'],//用户账号ID
                "userPhoneNumber" => "ALIPAY",//承租人/企业手机号
                "userCertName" => $order['cert_name'],//承租人/企业姓名
                "userCertNo" => $order['cert_no'],//承租人/企业证件号
                "userCertFrontFileId" => $alipay_idcard_back['fileId'],//承租人身份证国徽面
                "userCertBackFileId" => $alipay_idcard_front['fileId'],//承租人身份证人像面 先调用文件上传的接口，这里填上传后返回的fileid
                "userAccountType" => "ALIPAY",//用户账号平台类型1.支付宝：ALIPAY
                "userCertType" =>"IDENTITY_CARD",//1.身份证：IDENTITY_CARD
            ]);

            $order_data=[
                "orderOuterId" => $order['id'],//订单外部ID
                "orderCreateTime" => date('c',$order['create_time']),//商家租赁订单创建时间
                "userInfo" => $bclUserInfo,//用户信息
                "orderWithholdType" => "PROXY_WITHHOLDING",//租金支付方式1.网商代扣：MY_BANK_PROXY_WITHHOLDING2.预授权代扣：PRE_AUTHORIZATION_WITHHOLDING 3.租赁代扣：PROXY_WITHHOLDING
//                "acutalPreAuthFree" => 1,//芝麻信用实际预授权金额，单位：分
                "userIp" => getRealIp(),//用户下单时的ip地址
                "totalRentMoney" => $amount_rent,//租金总额，单位：分 最小值需大于0
                "rentTerm" => $order['month_total'],//租期，单位：月 最小值需大于0
                "rentUnit" => "MONTH",//订单租期单位，1.月：MONTH例如：rent_term入参12，rent_unit入参MONTH代表租期12个月
                "dueMode" => "DUE_BUYOUT",//到期形式：1.到期买断：DUE_BUYOUT 2.到期归还：DUE_RETURN
                //"mybankAgreementNo" => "1",//代扣协议号
//                "realPersonReturnUrl" => "1",//承租人实人认证完成后回跳地址比如商户小程序下单地址，选择实人认证服务时必填
                //"mybankAgreementOrderId" => "1",//网商代扣受理订单号
//                "depositFree" => 1,//芝麻信用订单免押金额，单位：分
                "promiseDetails" =>$bclCreatePromiseDetailInfo,//承诺详情按期数从小到大且连续排序
                "productInfos" => [
                    $bclOrderProductInfo0//商品列表
                ],
                "logisticType" => "POST"//物流方式 1.邮寄：POST 2.线下自取：OFFLINE
            ];
            if($order['pact_type']==1){
                $order_data['buyOutPrice']=bcmul($order['setmeal_price'],100);//到期买断价，单位：分
            }
            $createBclOrderRequest = new CreateBclOrderRequest($order_data);
            $orderCreatedata=self::createOrder($createBclOrderRequest);
            $orderCreatedata=obToArray($orderCreatedata);

            self::requestLog('创建租赁宝订单',$order_data,$orderCreatedata);
            $resData=order::where('id',$orderId)->update(['zulinbao_order_id'=>$orderCreatedata['orderId']]);
            if($resData){
                return ['status'=>1];
            }else{
                return ['status'=>0, 'message'=>'创建失败'];
            }
        }
    }



    /**
     * uploadPerformance(履约信息上传)
     * 接口名：twc.notary.bcl.performance.upload
     * 接口说明：如果没有使用租赁代扣，或者变更履约方式为手动还款后，需要主动进行履约信息上传。
     * 前置条件：必须完成 租赁订单发起 接口，并且订单状态为 履约中。
     * @param string[] $args
     * @return void
     */
    public static function uploadPerformance($orderId,$period,$amount,$voucher_serial){
        $args= [
            "period" => $period,
            "amount" => $amount,
//            "premium" => 1280,//手续费，单位：分
            "voucherType" => "PLATFORM_COLLECTION",//还款凭证类型
            "time" => date('c',time()),
            "orderId" => $orderId,
            "way" => "ACTIVE_REPAYMENT",//归还方式 1.主动还款：ACTIVE_REPAYMENT 2.网商委托代扣：MY_BANK_PROXY_WITHHOLDING 3.预授权代扣：PRE_AUTHORIZATION_WITHHOLDING
            "voucherSerial" => $voucher_serial//还款凭证编号
        ];
        $uploadBclPerformanceRequest = new UploadBclPerformanceRequest($args);
        $result=(new self())->AntChainTWCClient->uploadBclPerformance($uploadBclPerformanceRequest);
        $result=obToArray($result);
        self::requestLog('履约信息上传',$args,$result);
        return $result;
    }

    /**
     *
     * updatePromiseRepayment(变更订单承诺履约还款方式)
     * 对于使用租赁代扣的方式的订单，可以选择变更其中单期的履约还款方式为主动还款。
     * 前置条件：必须完成租赁订单发起并且状态为履约中，租金支付方式为租赁代扣。
     * @param string[] $args
     * @return void
     */
    public static function updatePromiseRepayment($orderId,$period){
        $request=[
            "period" => $period,
            "orderId" => $orderId
        ];
        $updateBclPromiserepaymentRequest = new UpdateBclPromiserepaymentRequest($request);
        $result=(new self())->AntChainTWCClient->updateBclPromiserepayment($updateBclPromiserepaymentRequest);
        $result=obToArray($result);
        self::requestLog('变更订单承诺履约还款方式',$request,$result);
        return $result;
    }

    /**
     * 上传物流信息
     * @param string[] $args
     * @return void
     */
    public static function addLogisticInfo($args){
        $addBclLogisticinfoRequest = new AddBclLogisticinfoRequest($args);
        $result=(new self())->AntChainTWCClient->addBclLogisticinfo($addBclLogisticinfoRequest);
        $result=obToArray($result);

        self::requestLog('上传物流信息',$args,$result);
        return $result;
    }
    /**
     * 租赁订单查询
     * @param string[] $args
     * @return void
     */
    public static function queryOrder($args){
        $queryBclOrderRequest = new QueryBclOrderRequest([
            "orderId" => $args
        ]);
        $result=(new self())->AntChainTWCClient->queryBclOrder($queryBclOrderRequest);
        $result=obToArray($result);
        self::requestLog('上传物流信息',["orderId" => $args],$result);
        return $result;
    }

    /** 租赁订单发起
     * @param string[] $args
     * @return void
     */
    public static function submitOrder($zulinbao_order_id){
        $data=[
            "orderId" => $zulinbao_order_id
        ];
        $submitBclOrderRequest = new SubmitBclOrderRequest($data);

        $result=obToArray((new self())->AntChainTWCClient->submitBclOrder($submitBclOrderRequest));
        self::requestLog('租赁订单发起',$data,$result);
        return $result;
    }

    /**创建租赁订单
     * @param string[] $args
     * @return void
     */
    public static function createOrder($args){
        return  (new self())->AntChainTWCClient->createBclOrder($args);
    }
    /**
     * 商品查询
     * @param string[] $args
     * @return void
     */
    public static function queryBclProduct($args){
        $queryBclProductRequest = new QueryBclProductRequest([
            "productId" => "10"
        ]);
        return  (new self())->AntChainTWCClient->queryBclProduct($queryBclProductRequest);
    }
    /**商品明细导入
     * @param string[] $args
     * @return void
     */
    public static function createProduct(array $args){
        $createBclProductRequest = new CreateBclProductRequest($args);
        return (new self())->AntChainTWCClient->createBclProduct($createBclProductRequest);
    }

    /**
     * 租赁订单承诺信息查询
     * @param $orderId
     * @return array
     * @throws \AntCloudSDKCore\Exception\ClientException
     */
    public static function leaseQuery($orderId){
                // 构建请求
        $client = new AntCloudClient(config('antchain.endpoint'),config('antchain.accessKeyId'),config('antchain.accessKeySecret'));
        $request = array(
                    "biz_content" => json_encode(['orderId'=>$orderId]),
                    "type" => "order",
                    "method"=>'twc.notary.lease.biz.query',
                    "version"=>'1.0',
                    "product_instance_id" => 'notary-api-test',
                    'region_name'=>'CN-HANGZHOU-FINANCE',
                );
//        $client = self::antChainClient();
        $response = $client->execute($request);
        dd($response);
        if($response['result_code'] == self::ANTCHAIN_SUCCESS_CODE){
            $flag = true;
        }
        self::requestLog('用户注册',$request,$response);
        return ['status'=>$flag, 'message'=>$flag ? '成功' : $response['result_msg'],'data'=>$flag ? $response['user_id'] : $response];
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function getBclUploadurl($args,$filename){
        $getBclUploadurlRequest = new GetBclUploadurlRequest([ "fileName" => $filename]);

        $getUploadInfo=(new self())->AntChainTWCClient->getBclUploadurl($getBclUploadurlRequest);
        $getUploadInfo=obToArray($getUploadInfo);

        $fileName = $filename; // 文件名
        $tenantId = config('antchain.TENANTID'); // 租户ID
        $localFile = $args; // 实际的本地文件路径
        $url = $getUploadInfo['url']; // 实际的OSS URL
// 初始化cURL会话
        $ch = curl_init();

// 设置cURL选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/octet-stream',
            'x-oss-meta-rawfilename: ' . $fileName,
            'x-oss-meta-rawtenantid: ' . $tenantId,
        ));
        curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($localFile));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 执行cURL请求
        $response = curl_exec($ch);

// 检查请求是否成功
        if ($response === false) {
            echo "cURL Error: " . curl_error($ch);
        } else {
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if ($httpCode === 200) {
                 $data=['status'=>$httpCode,'fileId'=>$getUploadInfo['fileId']];
            } else {
                $data=['status'=>$httpCode,'fileId'=>"文件上传失败！HTTP状态码：" . $httpCode];
            }
        }
// 关闭cURL会话
        curl_close($ch);
        return $data;
    }

    /**注册商户
     * @param string[] $args
     * @return void
     */
    public static function registerBclMerchant(){
        $bclContactInfo0 = new BclContactInfo([
            "phone" => "19357616167",
            "name" => "吴力军",
            "mobile" => "19357616167"
        ]);
        $registerBclMerchantRequest = new RegisterBclMerchantRequest([
            "clientToken" => "ACy4VGdEiUEiZbpM",
            "needProxyWithholding" => true,
            "certNo" => "91330381MAC65FWH5X",
            "legalCertNo" => "330381198507130013",
            "name" => "瑞安市诺明网络科技有限公司",
            "legalName" => "吴力军",
            "aliasName" => "都来租物",
            "managementType" => "DIGITAL_LEASE",
            "contactInfos" => [
                $bclContactInfo0
            ],
            "merchantType" => "ENTERPRISE",
            "alipayLogonId" => "19357616167@163.com"
        ]);
       return  (new self())->AntChainTWCClient->registerBclMerchant($registerBclMerchantRequest);
    }

    /**
     * 智能合同
     * @return AntCloudClient
     */
    public static function antChainClient()
    {
        $client = new AntCloudClient(config('antchain.endpoint'),config('antchain.accessKeyId'),config('antchain.accessKeySecret'));
        return $client;
    }
}

